package com.beike.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beike.common.PageResult;
import com.beike.entity.User;
import com.beike.entity.UserRole;
import com.beike.entity.UserStatus;
import com.beike.mapper.UserMapper;
import com.beike.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    
    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserRole login(String username, String password, UserRole expectedRole) {
        // 打印调试信息
        System.out.println("Attempting login - username: " + username + ", expected role: " + expectedRole);
        System.out.println("Expected role value: " + expectedRole.getValue());
        
        User user = userMapper.findByUsernameAndPassword(username, password);
        
        if (user == null) {
            System.out.println("User not found or password incorrect");
            return null;
        }
        
        System.out.println("Found user: " + user);
        System.out.println("Found user role: " + user.getRole());
        System.out.println("Found user role value: " + (user.getRole() != null ? user.getRole().getValue() : "null"));
        
        if (user.getRole() == expectedRole) {
            if (UserStatus.DISABLED.equals(user.getStatus())) {
                System.out.println("User account is disabled");
                throw new RuntimeException("账号已被禁用");
            }
            System.out.println("Login successful");
            return user.getRole();
        }
        
        System.out.println("Role mismatch - expected: " + expectedRole + ", actual: " + user.getRole());
        return null;
    }

    @Override
    public User createUser(User user) {
        if (userMapper.findByUsername(user.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        user.setPassword("123456"); // 设置默认密码
        
        if (user.getRole() == UserRole.STUDENT && !StringUtils.hasText(user.getStudentId())) {
            throw new RuntimeException("学生必须填写学号");
        }
        
        userMapper.insert(user);
        return user;
    }

    @Override
    public User updateUser(Long id, User user) {
        User existingUser = userMapper.findByUsername(user.getUsername());
        if (existingUser != null && !existingUser.getId().equals(id)) {
            throw new RuntimeException("用户名已存在");
        }
        
        user.setId(id);
        userMapper.updateById(user);
        return user;
    }

    @Override
    public void deleteUser(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectList(null);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public void resetPassword(Long id) {
        userMapper.updatePassword(id, "123456");
    }

    @Override
    public void updateStatus(Long id, String status) {
        try {
            UserStatus userStatus = UserStatus.fromValue(status);
            userMapper.updateStatus(id, userStatus.getValue());
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("Invalid status value: " + status);
        }
    }

    @Override
    public PageResult<User> getUsersByPage(String username, String name, UserRole role, 
            String status, int current, int pageSize) {
        // 创建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(username)) {
            queryWrapper.like(User::getUsername, username);
        }
        if (StringUtils.hasText(name)) {
            queryWrapper.like(User::getName, name);
        }
        if (role != null) {
            queryWrapper.eq(User::getRole, role);
        }
        if (StringUtils.hasText(status)) {
            queryWrapper.eq(User::getStatus, status);
        }
        
        // 执行分页查询
        Page<User> page = userMapper.selectPage(new Page<>(current, pageSize), queryWrapper);
        
        return new PageResult<>(page.getRecords(), page.getTotal(), pageSize, current);
    }
}
